package leetcode;

/**
 * @author Liangyaoyun
 */
public class addTwoNumbers {


   // Definition for singly-linked list.
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode result=new ListNode(0);
            ListNode head=result;
            int carry=0;
            while(l1!=null||l2!=null){
                int n1,n2;
                if(l1==null){
                    n1=0;
                }
                else{
                    n1=l1.val;
                }
                if(l2==null){
                    n2=0;
                }
                else{
                    n2=l2.val;
                }
                int sum = n1 + n2 + carry;
                //获取进位
                carry=sum/10;
                //获取两数相加的个位数值
                sum=sum%10;
                //将进位存到下个一节点
                head.next=new ListNode(carry);
                //更新节点
                head=head.next;
                //更新l1节点
                if(l1!=null){
                    l1=l1.next;
                }
                //更新l2节点
                if(l2!=null){
                    l2=l2.next;
                }

            }
            //判断最终位数是否是1，如果是1说明相加的两数值超过1000
            if(carry==1){
                head.next=new ListNode(carry);
            }
            return result.next;
        }
    }
}
